// pages/property/feeOrder/index.js
var app = getApp(), fetchApi = require("../../../utils/httpPost.js"), common_Js = require("../../../component/common.js")
import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageSize: 10,
    pageIndex: 1,
    isLoading: true,
    roomList: [],
    band_count: 0,
    estate_id: 0,
    estate_name: '',
    action: '',
    secondsMill: 60 * 1000,
    isSendMsg: false,
    submitState: false,
    phone_num: '',
    smsCode: '',
    showBand: false,
    feeType:'wyf', // 费用类型  wyf - 物业费  eletrict - 电费  water - 水费
    roomData:[],
    roomNo:'请选择户号',
    roomId:0,
    isShowPopup:false,
    searchValue:'',
    columns: [
        {
            values: [],
            className: 'column1',
            defaultIndex: 0
        },
        {
            values: [],
            className: 'column2',
            defaultIndex: 0
        },
        {
            values: [],
            className: 'column3',
            defaultIndex: -1
        }
    ],
    is_need_sms_band_room: 0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.type){
      this.data.feeType = options.type;
    }
    var is_need_sms_band_room = app.getStorageSync('is_need_sms_band_room');
    if(is_need_sms_band_room){
      this.data.is_need_sms_band_room = is_need_sms_band_room;
      this.setData({
        is_need_sms_band_room: is_need_sms_band_room
      })
    }
    let phone_num = app.getStorageSync('phone_num');
    if(phone_num){
      this.setData({
        phone_num: phone_num
      })
    }

    this.onHttpInit();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(this.data.estate_id > 0){
        this.onHttpEstateRoomList();
    }
  },  
  onChange(val){
    console.log('onChange',val)
    this.setData({
      searchValue: val.detail
    });
  },
  onSearch(val){
    console.log('onSearch',val)
    this.data.searchValue = val.detail;

    this.data.pageIndex = 1;
    this.setData({
      roomList:[]
    })
    this.onHttpInit()
  },
  onSearchClick(val){
    console.log('onSearchClick',val)
    this.data.pageIndex = 1;
    this.setData({
      roomList:[]
    })
    this.onHttpInit()
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpEstateRoomList: function () {
    var that = this
    fetchApi.httpPost('/estate/picker/detail', {
      estate_id: that.data.estate_id,
    }, function (res) {
      console.log("该小区下的房间列表的树形结构", res)
      if (res.data.code == 0) {
          that.data.roomData = res.data.data.roomsList;
          
        that.setData({
            roomData: res.data.data.roomsList
        })
        // 默认展示一级的数据
        that.data.columns[0].values = res.data.data.roomsList
        //  Object.values().map(function(e){
        //     return {text:e.text,level:e.level,index:e.index}
        // })
        // 默认展示二级的数据
        that.data.columns[1].values = res.data.data.roomsList[0].values
        //  Object.values().map(function(e){
        //     return {text:e.text,level:e.level,index:e.index}
        // })
        // 默认展示三级的数据
        that.data.columns[2].values = res.data.data.roomsList[0].values[0].values
        //  Object.values().map(function(e){
        //     return {text:e.text,level:e.level,index:e.index}
        // })
        // console.log('that.data.columns',that.data.columns)
        that.data.roomId =  that.data.columns[2].values[0].roomId;
        that.data.roomNo =  that.data.columns[0].values[0].name + '-' + that.data.columns[1].values[0].name +'-'+ that.data.columns[2].values[0].name;
        
        that.setData({
            columns: that.data.columns,
            roomNo:that.data.roomNo,
        })
      }
    }, function (res) {
    })
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this
    fetchApi.httpPost('/estate/room/list', {
      keyword: that.data.searchValue,
    }, function (res) {
      console.log("我绑定的房间列表", res)
      if (res.data.code == 0) {
        that.data.band_count = res.data.data.band_count;
        that.setData({
          band_count: res.data.data.band_count,
          showBand: res.data.data.band_count == 0 ? true : false
        })
        if (res.data.totalcount > 0) {
          var rooms = res.data.data.rooms;
          console.log('rooms',rooms)
          for (var index in rooms) {
            that.data.roomList.splice(that.data.roomList.length, 0, rooms[index]);
          }
          that.setData({
            hasData: true,
            roomList: that.data.roomList
          })
        }
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  
  getPhoneNumber(e){
    console.log('getPhoneNumber', e)
    var that = this;
    fetchApi.httpPost('/user/getWxPhoneNum', { 
      code: e.detail.code, 
      user_type : 0,
    }, function (res) {
        if(res.data.code == 0){
          Toast.success(res.data.msg)
          that.data.phone_num = res.data.data;
          that.setData({
            phone_num: res.data.data
          })
          app.setStorageSync("phone_num", res.data.data);
        }else{
          Toast.fail(res.data.msg)
        }
    });
  },
  goBandRoom(){
    var isLogin = app.getStorageSync("isLogin");
    this.setData({ isLogin: isLogin})
    if(isLogin == 1){
        this.setData({
          showBand: !this.data.showBand,
        })
    }else{
        wx.navigateTo({
          url: '/pages/login/index',
        })
    }
  },
  goDelRoom(e){
    console.log('goDelRoom e',e)
    var roomId = e.currentTarget.dataset.id;
    var that = this;
    var message = "是否解绑该房屋？"
    Dialog.confirm({
      title: '房屋解绑',
      message
    }).then(() => {
      that.onHttpUnBandRoom(roomId)
    })
    .catch(() => {
      Dialog.close();
    });
  },
  onHttpUnBandRoom(roomId){
    var that = this;
    fetchApi.httpPost('/estate/unBandRoom', {
          room_id: roomId,
        }, function (res) {
          console.log("信息绑定返回", res)
          if (res.data.code == 0) {
            that.data.submitState = false;
            that.setData({submitState : false })
            Toast.success(res.data.msg);
            that.initData();
          }else{
            that.data.submitState = false;
            that.setData({submitState : false })
            Toast.fail( res.data.msg);
            return;
          }
        },function(){})
  },
  onChangeRoom(e){
    var that = this;
    console.log('onChangeRoom',e);

    //选择的是第几个
    var selectIndex = e.detail.index;

    var buildIndex = parseInt(e.detail.value[0].index);
    var unitIndex = parseInt(e.detail.value[1].index);
    var roomIndex = parseInt(e.detail.value[2].index);

    var build = that.data.roomData[buildIndex];
    // console.log('buildIndex',buildIndex)
    // console.log('that.data.roomData',that.data.roomData)
    // console.log('that.data.roomData[buildIndex].values',that.data.roomData[buildIndex].values)
    

    that.data.columns[1].values = that.data.roomData[buildIndex].values;
    // 默认展示三级的数据
    that.data.columns[2].values = that.data.roomData[buildIndex].values[unitIndex].values;
    
    const { picker, value, index } = e.detail;
    // 默认展示二级的数据
    if(selectIndex == 0){
      that.data.columns[1].defaultIndex = 0;
      that.data.columns[2].defaultIndex = 0;

      var roomNo = e.detail.value[0].name + '-';
      roomNo += that.data.columns[1].values[0].name +'-'+ that.data.columns[2].values[0].name;

      console.log('roomNo',roomNo)
      that.setData({
          roomNo: roomNo,
      })
      this.data.roomId = that.data.columns[2].values[0].roomId;
      console.log('this.data.roomId', this.data.roomId)

    }else if(selectIndex == 1){
      that.data.columns[2].defaultIndex = 0;
      var roomNo = e.detail.value[0].name + '-' + e.detail.value[1].name + '-';
      roomNo += that.data.columns[2].values[0].name;

      console.log('roomNo',roomNo)
      that.setData({
          roomNo: roomNo,
      })
      this.data.roomId = that.data.columns[2].values[0].roomId;
      console.log('this.data.roomId', this.data.roomId)


    }else{
      that.data.columns[2].defaultIndex = 0;
      var roomNo = e.detail.value[0].name + '-' + e.detail.value[1].name + '-' + e.detail.value[2].name;
      console.log('roomNo',roomNo)
      that.setData({
          roomNo: roomNo,
      })
      this.data.roomId = e.detail.value[2].roomId;
      console.log('this.data.roomId', this.data.roomId)
    }
    that.setData({
        columns: that.data.columns,
    })
  },
  onClickEstate() {
    console.log('onClickEstate')
    wx.navigateTo({
      url: '/pages/estate/list/index',
    })
  },
  onClickRoom(){
    this.setData({
        isShowPopup : !this.data.isShowPopup,
    })
  },
  onChange(e) {
      this.setData({
          secondsMill: e.detail
      });
  },
  goWyfList(e){
    var roomId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pagesProperty/pages/feeList/index?room_id=' + roomId+'&type='+ this.data.feeType,
    });
  },
  handleTimCount(){
    if(this.data.phone_num == ''){
      Toast.fail("请输入手机号");
      return ;
    }
    if(this.data.phone_num.length != 11){
      Toast.fail("请输入11位手机号");
      return ;
    }
    
    if(this.data.estate_id == 0){
      Toast.fail("请选择所属小区");
      return;
    }

    this.sendSmgCode();
  },
  bindInput(e){
    console.log('bindInput e',e)
    var key = e.currentTarget.dataset.key;
    var input  = e.detail;
    if(key == 'phone'){
      this.data.phone_num = input;
    }else if(key == 'code'){
      this.data.smsCode = input;
    }
  },
  sendSmgCode(){
    var that = this;
    fetchApi.httpPost('/estate/sendCode', {
      phoneNum: that.data.phone_num,
      estate_id: that.data.estate_id,      
    }, function (res) {
      console.log("获取验证码", res)
      if (res.data.code == 0) {
        Toast.success(res.data.msg);
        that.setData({
          isSendMsg: !that.data.isSendMsg
        })
      }else{
        Toast.fail( res.data.msg);
      }
    },function(){})
  },
  /**
   * 绑定操作操作
   */
  bandSubmitOp:function(){
    var that = this;
    if (that.data.estate_id == 0){
      Toast.fail('请选择所在小区');
      return;
    }

    if (that.data.phone_num.length <= 0){
        Toast.fail('手机号不能为空');
        return;
    }

    // if(that.data.roomNo == '' || that.data.roomNo == '请选择户号'){
    //     Toast.fail('请选择户号');
    //     return;
    // }

    // if(this.data.is_need_sms_band_room == 1){
    //   if(that.data.smsCode == '' ){
    //     Toast.fail('验证码不能为空');
    //     return;
    //   }
    // }

    if(that.data.submitState){
        Toast.fail('正在提交...');
        return;
    }

    that.data.submitState = true;
    that.setData({submitState : true })

    fetchApi.httpPost('/estate/bandRoom', {
      phone_num: that.data.phone_num,
      estate_id: that.data.estate_id,
      code:that.data.smsCode,
      // room_no: that.data.roomNo,
      // room_id:that.data.roomId,
    }, function (res) {
      console.log("信息绑定返回", res)
      if (res.data.code == 0) {
        that.data.submitState = false;
        that.data.roomNo = '请选择户号';
        that.data.roomId = 0;
        that.setData({
            submitState : false,
            roomNo:'请选择户号' 
        })
        that.setData({
          showBand: !that.data.showBand,
        })
        Toast.success(res.data.msg);
        that.initData();
      }else{
        that.data.submitState = false;
        that.data.roomNo = '请选择户号';
        that.data.roomId = 0;
        that.setData({
            submitState : false,
            roomNo:'请选择户号'  
        })
        that.setData({
          showBand: !that.data.showBand,
        })
        Toast.fail( res.data.msg);
        return;
      }
    },function(){})
  },
  initData(){
    this.data.pageIndex = 1;
    this.setData({
      roomList: [],
    })
    this.onHttpInit();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.initData();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // this.onHttpInit();
  },
})